package org.example.leetcpde;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

public class GenerateParenthesis {

    @Test
    void run() {
        List<String> strings = generateParenthesis(3);
        strings.forEach(System.out::println);
    }

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        dfs(new StringBuilder(), n , n , n, res);
        return res;
    }

    void dfs(StringBuilder state,
             int left,
             int right,
             int n,
             List<String> res) {

        if (state.length() == n << 1) {
            res.add(state.toString());
            return;
        }

        if (left > 0) {
            dfs(state.append("("), left - 1, right, n, res);
            state.deleteCharAt(state.length() - 1);
        }

        if (left < right) {
            dfs(state.append( ")"), left, right - 1, n, res);
            state.deleteCharAt(state.length() - 1);
        }
    }

}
